package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.SetMealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {

    //持久层对象
    @Autowired
    private SetMealMapper setMealMapper;
    //redis连接池对象
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //新增数据  并封装id
        setMealMapper.add(setmeal);
        //获取id
        Integer setmealId = setmeal.getId();
        //添加与检查组的关联数据
        setSetMealIdAndCheckgroupIds(setmealId, checkgroupIds);
        //存入redis 此时图片值已经在数据库 所以可以存入redis的数据库集合部分.
        String fileName = setmeal.getImg();
        if (fileName != null) {
            Jedis resource = jedisPool.getResource();
            resource.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);
            //释放资源
            resource.close();
        }

        //添加完成 更新一下静态页面
        //generateMobileStaticHtml();
    }

    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //分页操作
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> setmeals = setMealMapper.findByCondition(queryString);
        return new PageResult(setmeals.getTotal(), setmeals.getResult());
    }

    @Override
    public List<Integer> findCheckgroupIds(Integer setmealId) {
        return setMealMapper.findCheckgroupIds(setmealId);
    }

    @Override
    public List<Setmeal> getAllSetmeal() {
        return setMealMapper.getAllSetmeal();
    }

    @Override
    public Setmeal findById(Integer id) {
        return setMealMapper.findById(id);
    }

    //添加与检查组的关联数据
    private void setSetMealIdAndCheckgroupIds(Integer setmealId, Integer[] checkgroupIds) {
        //对数组判空
        if (checkgroupIds != null) {
            for (Integer checkgroupId : checkgroupIds) {
                Map map = new HashMap();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                //添加关联表数据
                setMealMapper.setSetMealIdAndCheckgroupId(map);
            }
        }
    }

    //更新静态页面 包括套餐列表页面和详情页面
    public void generateMobileStaticHtml() {
        //生成之前查询数据
        List<Setmeal> list = setMealMapper.getAllSetmeal();

        //生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //生成套餐详情页面
        generateMobileSetmealDetailHtml(list);

    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //保存基本数据
        setMealMapper.edit(setmeal);
        //获取setmealId
        Integer setmealId = setmeal.getId();
        //删除所有外键关联
        setMealMapper.deleteAssociation(setmealId);
        //添加新的外键关联
        setCheckgroupIdsBySetmealId(checkgroupIds,setmealId);
        //更新静态页面
        //generateMobileStaticHtml();
    }

    @Override
    public void deleteById(Integer id) {
        //先删除外键关联
        setMealMapper.deleteAssociation(id);
        //删除本体
        setMealMapper.deleteById(id);
        //更新静态页面
        //generateMobileStaticHtml();
    }

    @Override
    public List<String> getAllImg() {
        return setMealMapper.getAllImg();
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setMealMapper.findSetmealCount();
    }


    private void setCheckgroupIdsBySetmealId(Integer[] checkgroupIds, Integer setmealId) {
        for (Integer checkgroupId : checkgroupIds) {
            Map map = new HashMap();
            map.put("checkgroupId",checkgroupId);
            map.put("setmealId",setmealId);
            setMealMapper.setCheckgroupIdBySetmealId(map);
        }
    }

    private void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map map = new HashMap();
        //为模板提供静态数据, 用于生成静态页面
        map.put("setmealList",list);
        generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    private void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        //套餐详情页面 需要生成多个
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setMealMapper.findById(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }

    //通过方法 用于生成静态页面
    public void generateHtml(String templateName, String htmlPageName, Map map) {
        //获得配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
